import {
	baseUrl
} from './config.js'

function http(url, data = {}, method = 'POST', showLoading = false, showMessage =
	true, header = {
		'content-type': 'application/json'
	}) {
	return new Promise((resolve, reject) => {
		if (showLoading) {
			uni.showLoading({
				mask: true
			})
		}
		if(!uni.getStorageSync('uinfo')&&url!='/api/login'){
			uni.navigateTo({
				url:'../login/login'
			})
		}
		uni.request({
			url: baseUrl + url,
			data: data,
			method: method,
			header: header,
			success(res) {
				uni.hideLoading()
				uni.stopPullDownRefresh()
				if (res.data.code == 200) {
					resolve(res.data);
				} else {
					// token过期
					if (res.data.msg == '访问令牌过期或无效' || res.data.msg ==
						'缺少访问令牌') {
						uni.showToast({
							title: '请先登录',
							icon: 'none',
							duration: 3000
						})
						uni.clearStorageSync()
						setTimeout(function() {
							uni.reLaunch({
								url: '/pages/login/login'
							})
						}, 1500)
						return
					}
					if (showMessage) {
						uni.showToast({
							title: res.data.msg || '操作失败，请检查信息后再试',
							icon: 'none',
							duration: 3000
						})
					}


					reject(res.data)
				}
			},
			fail(res) {
				if (showMessage) {
					uni.showToast({
						title: '连接服务器失败,请稍后重试!',
						icon: 'none',
						duration: 3000
					})
				}
				uni.hideLoading()
			}
		})
	})

}
export default http;
